<template>
  <CallNotification />
  <RouterView />
</template>

<script setup lang="ts">
import CallNotification from '@/components/CallNotification.vue'
import {onMounted, onUnmounted, provide, ref, watch} from 'vue'
import { useCallStore } from '@/stores/call'

declare global {
  interface Window {
    $http: any;
    testNotify?: () => void
  }
}

const callStore = useCallStore()
const ws = ref<WebSocket | null>(null)  // 存储WebSocket连接引用
const token = ref(localStorage.getItem('token')) // 获取Token
const userId = ref('-1') // 存储解析后的用户id

provide('websocket', ws)  // 暴露WebSocket给所有子组件

// 调试工具函数
const getSocketState = (state: number) => {
  const states = {
    0: 'CONNECTING',
    1: 'OPEN',
    2: 'CLOSING',
    3: 'CLOSED'
  };
  return states[state as keyof typeof states] || `UNKNOWN (${state})`;
};

// 周期性状态检查
const debugInterval = ref<NodeJS.Timeout>();

onMounted(() => {
  window.addEventListener('ws-message', (event) => {
    const message = (event as CustomEvent).detail;
    if (message.type === 'sync') handleSyncMessage(message);
  });
  setupTokenWatcher();

  // 每10秒输出连接状态
  debugInterval.value = setInterval(() => {
    if (!ws.value) {
      console.log('WebSocket未初始化');
      return;
    }

    const stateMap = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
    console.log(
        `连接状态: ${stateMap[ws.value.readyState]}`,
        `状态: ${callStore.callStatus}`
    );

    // 每10s一次主动发送Ping检测
    if (ws.value.readyState === WebSocket.OPEN) {
      try {
        ws.value.send(JSON.stringify({ type: 'ping' }));
      } catch (e) {
        console.error('Ping发送失败:', e);
      }
    }
  }, 10000);
  console.log('初始化WebSocket监控系统');
});

// 全局消息处理器
const handleSyncMessage = (message: { type: string; data: any }) => {
  if (message.type === 'sync') {
    console.log('收到状态同步:', message.data);
    // 强制更新连接状态
    if (ws.value) {
      ws.value.onopen = null;
      ws.value.dispatchEvent(new Event('open')); // 手动触发open
    }
  }
};

// 工具函数：从Token解析用户ID
const getUserIdFromToken = (token: string) => {
  if (!token) return '';
  try {
    const payloadBase64 = token.split('.')[1];
    const decoded = JSON.parse(atob(payloadBase64));
    return decoded.sub;
  } catch (error) {
    console.error('Token解析失败:', error);
    return '';
  }
};

/**
 * 初始化WebSocket连接
 */
const initWebSocket = (userId: string) => {
  // 关闭旧连接
  if (ws.value?.readyState === WebSocket.OPEN) {
    ws.value.close()
  }

  ws.value = new WebSocket(`ws://192.168.1.17:8010/signaling?userId=${userId}`)

  // 统一消息处理
  ws.value.onmessage = (event) => {
    console.log('原始WebSocket消息:', event.data)
    try {
      const message = JSON.parse(event.data)

      // 保持原有全局事件触发机制
      window.dispatchEvent(new CustomEvent('ws-message', {
        detail: message,
        bubbles: true,
        composed: true
      }))

      // 特殊处理邀请消息
      if (message.type === 'invitation') {
        console.log('直接处理邀请消息', message)
        callStore.receiveCall({
          roomId: message.roomId,
          callerId: message.senderId,
          callerName: message.data?.callerName || message.senderId
        })
      }
    } catch (e) {
      console.error('消息解析失败:', e)
    }
  }

  ws.value.onopen = () => {
    console.log('WebSocket连接成功')
    // 加入默认房间
    ws.value?.send(JSON.stringify({
      type: 'join',
      roomId: 'default_room',
      senderId: userId
    }))
  }

  ws.value.onerror = (e) => {
    console.error('连接错误:', e)
    // 5秒后自动重连
    setTimeout(() => userId && initWebSocket(userId), 5000)
  }

  ws.value.onclose = () => {
    console.log('no！！！！！！！')
  }
}

watch(token, (newToken) => {
  console.log('检测到token变化:', newToken)

  // 解析用户ID
  const newUserId = getUserIdFromToken(newToken)
  console.log('解析后的用户ID:', newUserId)

  // 关闭旧连接
  const closeConnection = () => {
    return new Promise<void>((resolve) => {
      if (!ws.value || ws.value.readyState === WebSocket.CLOSED) {
        return resolve()
      }
      ws.value.onclose = () => {
        console.log('旧连接已完全关闭')
        resolve()
      }
      ws.value.close()
    })
  }

  // 建立新连接
  closeConnection().then(() => {
    if (newUserId && newUserId !== '-1') {
      console.log('正在为用户ID建立连接:', newUserId)
      // 先更新userId再初始化连接
      userId.value = newUserId
      initWebSocket(newUserId)
    }
  })
}, { immediate: true })

// 监听 localStorage 变化的函数
const setupTokenWatcher = () => {
  // 确保在添加监听器前先同步值
  const initialToken = localStorage.getItem('token') || ''
  token.value = initialToken
  console.log('初始token同步:', initialToken)

  window.addEventListener('storage', (event) => {
    if (event.key === 'token') {
      token.value = event.newValue || ''
    }
  })

  const originalSetItem = localStorage.setItem.bind(localStorage)
  localStorage.setItem = (key, value) => {
    if (key === 'token') {
      token.value = value
    }
    originalSetItem(key, value)
  }
}

const handleWsMessage = (event: Event) => {
  const message = (event as CustomEvent).detail as {
    type: string;
    roomId: string;
    senderId: string;
    data: any;
  };
  console.log('收到原始消息:', message);

  if (message.type === 'invitation') {
    console.log('触发邀请通知', message);
    callStore.receiveCall({
      roomId: message.roomId,
      callerId: message.senderId,
      callerName: message.data?.callerName || message.senderId
    });
  }
};

onMounted(() => {
  window.addEventListener('ws-message', handleWsMessage)
  setupTokenWatcher()

  window.addEventListener('ws-message', (event) => {
    const message = (event as CustomEvent).detail;
    if (message.type === 'sync') handleSyncMessage(message);
  });

  window.removeEventListener('ws-message', handleWsMessage);

  if (ws.value) {
    ws.value.close();
    ws.value = null;
  }
})

// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  window.removeEventListener('ws-message', handleWsMessage); // 清理监听
  if (ws.value) {
    ws.value.close() // 关闭连接
    ws.value = null
  }
})
</script>

<style scoped>
</style>